<template>
  <div class="container">

    <div class="content-wrapper">
      <el-row :gutter="20">
        <el-col :span="5" class="left-col">
          <div class="area-management">
            <div class="section-header">
              <el-icon><FolderOpened /></el-icon>
              <span>区域管理</span>
            </div>
            <el-button
                class="add-btn"
                @click="dialogVisibleRegion = true"
                type="primary"
                round
            >
              <img src="@/components/deviceicons/plus-circle.png" style="width: 20px; margin-right: 10px" alt="icon">
              新增区域
            </el-button>
            <div class="tree-container">
              <el-tree
                  :data="treeData"
                  :props="defaultProps"
                  :disable-branch-nodes="true"
                  highlight-current
                  default-expand-all
                  @node-click="handleNodeClick"
                  class="custom-tree"
              />
            </div>
          </div>
        </el-col>

        <el-col :span="19" class="right-col">
          <div class="device-management">
            <div class="section-header">
              <el-icon><Camera /></el-icon>
              <span>设备管理</span>
            </div>

            <div class="device-controls">
              <el-button type="primary" @click="dialogVisibleDevice = true" round
              >新增设备</el-button
              >
              <el-button id="delbtn" type="danger" round @click="handleBatchDelete"
              >批量删除</el-button
              >
              <div class="search-box">
                <el-input
                    v-model="searchKeyword"
                    placeholder="搜索设备名称、IP或区域"
                    clearable
                    @clear="handleSearchClear"
                    @keyup.enter="handleSearch"
                >
                  <template #append>
                    <el-button @click = "handleSearch" :icon="Search"/>
                  </template>
                </el-input>
              </div>
            </div>

            <div class="device-table">
              <el-table
                  class="custom-table"
                  :data="camera_data.tableData"
                  height="65vh"
                  border
                  stripe
                  @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="序号" type="index" width="80" align="center">
                  <template #default="scope">
                    <span v-text="getIndex(scope.$index)"></span>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="cameraName"
                    label="设备名称"
                    width="180"
                    align="center"
                    sortable
                >
                  <template #header>
                    <div class="table-header">
                      <span>设备名称</span>
                      <el-tooltip content="点击设备名称可查看详情" placement="top">
                        <el-icon><InfoFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="areaName"
                    label="区域名称"
                    width="200"
                    align="center"
                    sortable
                />
                <el-table-column prop="status" label="设备状态" width="150" align="center" sortable>
                  <template #default="{ row }">
                    <el-tag :type="getStatusTagType(row.status)" effect="light" round>
                      <span
                          :style="{
                          display: 'inline-block',
                          width: '8px',
                          height: '8px',
                          borderRadius: '50%',
                          marginRight: '6px',
                          backgroundColor: getStatusColor(row.status)
                        }"
                      ></span>
                      {{ row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="cameraIP" label="IP地址" width="170" align="center" />
                <el-table-column label="操作" align="center" width="180">
                  <template #default="scope">
                    <el-button
                        key="primary"
                        type="primary"
                        @click="handleEdit(scope.$index, scope.row)"
                        link
                        icon="Edit"
                    >
                      修改
                    </el-button>
                    <el-button
                        key="danger"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)"
                        link
                        icon="Delete"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="pagination-block">
              <el-pagination
                  v-model:current-page="camera_data.pageIndex"
                  v-model:page-size="camera_data.pageSize"
                  :page-sizes="pageSizes"
                  :small="small"
                  :disabled="disabled"
                  :background="background"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="camera_data.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 新增区域 Dialog -->
    <el-dialog v-model="dialogVisibleRegion" title="新增区域" width="500px">
      <el-form
          :model="region_form"
          :rules="regionRules"
          label-width="100px"
          ref="formRefRegion"
          label-position="left"
      >
        <el-form-item prop="areaName" label="区域名称">
          <el-input v-model="region_form.areaName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item prop="areaType" label="区域类型">
          <el-select v-model="region_form.areaType" placeholder="请选择区域类型">
            <el-option label="监测区域" value="monitor" />
            <el-option label="保护区" value="protected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitRegion">确认</el-button>
          <el-button @click="dialogVisibleRegion = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 新增设备 Dialog -->
    <el-dialog
        v-model="dialogVisibleDevice"
        title="新增设备"
        width="700px"
        :before-close="handleClose"
    >
      <el-form :model="camera_form" :rules="deviceRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="cameraName" label="设备名称">
              <el-input v-model="camera_form.cameraName" placeholder="请输入设备名称" />
            </el-form-item>
            <el-form-item prop="cameraIP" label="摄像头IP">
              <el-input v-model="camera_form.cameraIP" placeholder="例如：192.168.1.100" />
            </el-form-item>
            <el-form-item prop="loginUser" label="登录账号">
              <el-input v-model="camera_form.loginUser" placeholder="请输入登录账号" />
            </el-form-item>
            <el-form-item prop="loginPW" label="登录密码">
              <el-input v-model="camera_form.loginPW" type="password" show-password placeholder="请输入登录密码" />
            </el-form-item>
            <el-form-item prop="cameraPort" label="摄像头端口">
              <el-input v-model="camera_form.cameraPort" placeholder="例如：554" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="longitude" label="点位经度">
              <el-input v-model="camera_form.longitude" placeholder="例如：116.4074" />
            </el-form-item>
            <el-form-item prop="latitude" label="点位纬度">
              <el-input v-model="camera_form.latitude" placeholder="例如：39.9042" />
            </el-form-item>
            <el-form-item prop="pullUrl" label="拉流地址">
              <el-input v-model="camera_form.pullUrl" placeholder="请输入拉流地址" />
            </el-form-item>
            <el-form-item prop="pushUrl" label="推流地址">
              <el-input v-model="camera_form.pushUrl" placeholder="请输入推流地址" />
            </el-form-item>
            <el-form-item prop="hlsUrl" label="HLS地址">
              <el-input v-model="camera_form.hlsUrl" placeholder="请输入HLS地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="areaName" label="所属区域">
          <el-select v-model="camera_form.areaName" placeholder="请选择区域" style="width: 100%">
            <el-option
                v-for="area in staticAreas"
                :key="area.areaName"
                :label="area.areaName"
                :value="area.areaName"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="form-footer">
          <el-button type="primary" @click="onSubmitCamera">确认</el-button>
          <el-button @click="dialogVisibleDevice = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改设备 Dialog -->
    <el-dialog
        v-model="dialogEditDevice"
        title="修改设备"
        width="700px"
        :before-close="handleClose"
    >
      <el-form :model="edit_camera_form" :rules="deviceRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="cameraName" label="设备名称">
              <el-input v-model="edit_camera_form.cameraName" />
            </el-form-item>
            <el-form-item prop="cameraIP" label="摄像头IP">
              <el-input v-model="edit_camera_form.cameraIP" />
            </el-form-item>
            <el-form-item prop="loginUser" label="登录账号">
              <el-input v-model="edit_camera_form.loginUser" />
            </el-form-item>
            <el-form-item prop="loginPW" label="登录密码">
              <el-input v-model="edit_camera_form.loginPW" type="password" show-password />
            </el-form-item>
            <el-form-item prop="cameraPort" label="摄像头端口">
              <el-input v-model="edit_camera_form.cameraPort" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="longitude" label="点位经度">
              <el-input v-model="edit_camera_form.longitude" />
            </el-form-item>
            <el-form-item prop="latitude" label="点位纬度">
              <el-input v-model="edit_camera_form.latitude" />
            </el-form-item>
            <el-form-item prop="pullUrl" label="拉流地址">
              <el-input v-model="edit_camera_form.pullUrl" />
            </el-form-item>
            <el-form-item prop="pushUrl" label="推流地址">
              <el-input v-model="edit_camera_form.pushUrl" />
            </el-form-item>
            <el-form-item prop="hlsUrl" label="HLS地址">
              <el-input v-model="edit_camera_form.hlsUrl" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="areaName" label="所属区域">
          <el-select v-model="edit_camera_form.areaName" placeholder="请选择区域" style="width: 100%">
            <el-option
                v-for="area in staticAreas"
                :key="area.areaName"
                :label="area.areaName"
                :value="area.areaName"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="form-footer">
          <el-button type="primary" @click="editSubmit">确认</el-button>
          <el-button @click="dialogEditDevice = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 删除设备 Dialog -->
    <el-dialog v-model="deleteCameraVisible" title="删除设备" width="400px">
      <div class="delete-confirm">
        <el-icon color="#F56C6C" size="24px"><Warning /></el-icon>
        <div class="confirm-text">
          确认删除设备 <strong>{{ remove_camera.cameraName }}</strong> 吗？
        </div>
        <div class="confirm-hint">
          此操作将永久删除该设备信息，且不可恢复
        </div>
        <el-input
            v-model="input_delete_data"
            placeholder="请输入：确认删除"
            class="custom-input"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteCameraVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteCamera">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量删除 Dialog -->
    <el-dialog v-model="batchDeleteVisible" title="批量删除设备" width="400px">
      <div class="batch-delete-confirm">
        <el-icon color="#F56C6C" size="24px"><Warning /></el-icon>
        <div class="confirm-text">
          确认删除选中的 <strong>{{ selectedCameras.length }}</strong> 个设备吗？
        </div>
        <div class="confirm-hint">
          此操作将永久删除这些设备信息，且不可恢复
        </div>
        <el-input
            v-model="batch_delete_data"
            placeholder="请输入：确认删除"
            class="custom-input"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDeleteVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmBatchDelete">确认</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Camera, FolderOpened, Search,
  Warning, InfoFilled
} from '@element-plus/icons-vue';
import { useUserStore } from "@/store/user.js";

// 分页设置
const pageSizes = ref([5, 10, 20, 50]);
const small = ref(false);
const disabled = ref(false);
const background = ref(true);

// 搜索关键词
const searchKeyword = ref('');

// 数据加载和保存函数
const loadData = (key, staticData) => {
  const savedData = localStorage.getItem(key);
  if (savedData) {
    try {
      return JSON.parse(savedData);
    } catch (e) {
      console.error(`解析${key}数据失败:`, e);
      return [...staticData];
    }
  }
  return [...staticData];
};

const saveData = (key, data) => {
  try {
    localStorage.setItem(key, JSON.stringify(data));
  } catch (e) {
    console.error(`保存${key}数据失败:`, e);
    ElMessage.error("保存数据失败，可能已达到存储限制");
  }
};

// 初始静态区域数据
const initialStaticAreas = [
  { areaName: "东区湿地", areaType: "monitor" },
  { areaName: "西区森林", areaType: "protected" },
  { areaName: "南区公园", areaType: "monitor" },
  { areaName: "北区湖泊", areaType: "protected" },
  { areaName: "中心区", areaType: "monitor" }
];

// 初始静态摄像头数据
const initialStaticCameras = [
  {
    rowID: "cam001",
    cameraName: "湿地1号摄像头",
    companyName: "智能鸟类监测公司",
    areaName: "东区湿地",
    status: "在线",
    cameraIP: "192.168.1.101",
    cameraPort: "554",
    loginUser: "admin",
    loginPW: "123456",
    longitude: "116.4074",
    latitude: "39.9042",
    pullUrl: "http://192.168.1.101:8080/live/cam001.flv",
    pushUrl: "rtmp://192.168.1.101:1935/live/cam001",
    hlsUrl: "http://192.168.1.101:8080/live/cam001.m3u8"
  },
  {
    rowID: "cam002",
    cameraName: "森林1号摄像头",
    companyName: "智能鸟类监测公司",
    areaName: "西区森林",
    status: "离线",
    cameraIP: "192.168.1.102",
    cameraPort: "554",
    loginUser: "admin",
    loginPW: "123456",
    longitude: "116.3974",
    latitude: "39.9142",
    pullUrl: "http://192.168.1.102:8080/live/cam002.flv",
    pushUrl: "rtmp://192.168.1.102:1935/live/cam002",
    hlsUrl: "http://192.168.1.102:8080/live/cam002.m3u8"
  },
  {
    rowID: "cam003",
    cameraName: "公园1号摄像头",
    companyName: "智能鸟类监测公司",
    areaName: "南区公园",
    status: "故障",
    cameraIP: "192.168.1.103",
    cameraPort: "554",
    loginUser: "admin",
    loginPW: "123456",
    longitude: "116.4174",
    latitude: "39.8942",
    pullUrl: "http://192.168.1.103:8080/live/cam003.flv",
    pushUrl: "rtmp://192.168.1.103:1935/live/cam003",
    hlsUrl: "http://192.168.1.103:8080/live/cam003.m3u8"
  },
  {
    rowID: "cam004",
    cameraName: "湖泊1号摄像头",
    companyName: "智能鸟类监测公司",
    areaName: "北区湖泊",
    status: "在线",
    cameraIP: "192.168.1.104",
    cameraPort: "554",
    loginUser: "admin",
    loginPW: "123456",
    longitude: "116.4274",
    latitude: "39.9242",
    pullUrl: "http://192.168.1.104:8080/live/cam004.flv",
    pushUrl: "rtmp://192.168.1.104:1935/live/cam004",
    hlsUrl: "http://192.168.1.104:8080/live/cam004.m3u8"
  },
  {
    rowID: "cam005",
    cameraName: "中心区1号摄像头",
    companyName: "智能鸟类监测公司",
    areaName: "中心区",
    status: "在线",
    cameraIP: "192.168.1.105",
    cameraPort: "554",
    loginUser: "admin",
    loginPW: "123456",
    longitude: "116.4074",
    latitude: "39.9092",
    pullUrl: "http://192.168.1.105:8080/live/cam005.flv",
    pushUrl: "rtmp://192.168.1.105:1935/live/cam005",
    hlsUrl: "http://192.168.1.105:8080/live/cam005.m3u8"
  }
];

// 响应式数据
const areas = reactive({
  data: loadData('birdMonitoringAreas', initialStaticAreas)
});

const cameras = reactive({
  data: loadData('birdMonitoringCameras', initialStaticCameras)
});

// 监听数据变化并保存
watch(() => [...areas.data], (newVal) => {
  saveData('birdMonitoringAreas', newVal);
}, { deep: true });

watch(() => [...cameras.data], (newVal) => {
  saveData('birdMonitoringCameras', newVal);
}, { deep: true });

// 从pinia中获取公司名
const userStore = useUserStore();
const companyName = userStore.companyName;

// 树数据
const treeData = ref([
  {
    label: companyName,
    children: []
  }
]);

const defaultProps = {
  children: "children",
  label: "label"
};

// 点击树节点
const handleNodeClick = (node) => {
  console.log("点击了节点:", node);
  if (node.children == null) {
    // 区域筛选功能
    camera_data.pageIndex = 1;
    camera_data.tableData = cameras.data
        .filter(camera => camera.areaName === node.label)
        .slice(0, camera_data.pageSize);
    camera_data.total = cameras.data.filter(camera => camera.areaName === node.label).length;

    ElMessage.success(`已筛选区域: ${node.label}`);
  }
};

// 获取区域列表
const getAreaTable = () => {
  treeData.value[0].children = areas.data.map(area => ({
    label: area.areaName
  }));
  console.log("区域树数据:", treeData.value);
};
// 摄像头设备加分页数据
const camera_data = reactive({
  tableData: [],
  pageIndex: 1,
  total: cameras.data.length,
  pageSize: 10
});

// 获取表格序号
const getIndex = (index) => {
  return (camera_data.pageIndex - 1) * camera_data.pageSize + index + 1;
};

// 获取所有摄像头列表
const get_cameras = () => {
  const start = (camera_data.pageIndex - 1) * camera_data.pageSize;
  const end = start + camera_data.pageSize;
  camera_data.tableData = cameras.data.slice(start, end);
  camera_data.total = cameras.data.length;
};

// 每页大小
const handleSizeChange = (val) => {
  camera_data.pageSize = val;
  get_cameras();
};

// 当前页
const handleCurrentChange = (val) => {
  camera_data.pageIndex = val;
  get_cameras();
};

// 定义设备表单规则
const deviceRules = reactive({
  cameraName: [
    { required: true, message: "设备名称不能为空", trigger: "blur" },
    { min: 3, max: 20, message: "长度在3到20个字符", trigger: "blur" }
  ],
  cameraIP: [
    { required: true, message: "摄像头IP不能为空", trigger: "blur" },
    { pattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, message: "请输入正确的IP地址", trigger: "blur" }
  ],
  loginUser: [{ required: true, message: "摄像头登录账号不能为空", trigger: "blur" }],
  loginPW: [{ required: true, message: "摄像头登录密码不能为空", trigger: "blur" }],
  cameraPort: [
    { required: true, message: "摄像头端口号不能为空", trigger: "blur" },
    { pattern: /^[0-9]*$/, message: "端口号必须为数字", trigger: "blur" }
  ],
  longitude: [
    { required: true, message: "摄像头点位经度不能为空", trigger: "blur" },
    { pattern: /^-?\d{1,3}\.\d+$/, message: "请输入正确的经度", trigger: "blur" }
  ],
  latitude: [
    { required: true, message: "摄像头点位纬度不能为空", trigger: "blur" },
    { pattern: /^-?\d{1,3}\.\d+$/, message: "请输入正确的纬度", trigger: "blur" }
  ],
  pullUrl: [{ required: true, message: "摄像头拉流地址不能为空", trigger: "blur" }],
  pushUrl: [{ required: true, message: "摄像头推流不能为空", trigger: "blur" }],
  hlsUrl: [{ required: true, message: "摄像头HLS地址不能为空", trigger: "blur" }],
  areaName: [{ required: true, message: "请选择所属区域", trigger: "change" }]
});

// 定义区域表单规则
const regionRules = reactive({
  areaName: [
    { required: true, message: "区域名称不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "长度在2到10个字符", trigger: "blur" }
  ],
  areaType: [
    { required: true, message: "请选择区域类型", trigger: "change" }
  ]
});

// 区域表单
const region_form = reactive({
  areaName: "",
  areaType: "monitor"
});

// 新增区域dialog
const dialogVisibleRegion = ref(false);

// 提交新增区域信息
const onSubmitRegion = async () => {
  try {
    const newArea = {
      areaName: region_form.areaName,
      areaType: region_form.areaType
    };

    // 检查区域是否已存在
    if (areas.data.some(area => area.areaName === newArea.areaName)) {
      ElMessage.error("该区域名称已存在");
      return;
    }

    areas.data.push(newArea);
    getAreaTable();

    ElMessage({
      message: "区域添加成功",
      type: "success"
    });

    dialogVisibleRegion.value = false;
    region_form.areaName = "";
    region_form.areaType = "monitor";
  } catch (error) {
    console.error("添加区域失败:", error);
    ElMessage.error("添加区域失败");
  }
};

// 新增设备dialog
const dialogVisibleDevice = ref(false);

// 新增设备表单
const camera_form = reactive({
  cameraName: "",
  cameraIP: "",
  cameraPort: "",
  loginUser: "",
  loginPW: "",
  longitude: "",
  latitude: "",
  pullUrl: "http://xxx.xxx.xxx.xxx:8080/live/设备ID.flv",
  pushUrl: "rtmp://xxx.xxx.xxx.xxx:1935/live/设备ID",
  hlsUrl: "http://xxx.xxx.xxx.xxx:8080/live/设备ID.m3u8",
  areaName: ""
});

// 提交新增摄像头设备信息
const onSubmitCamera = async () => {
  try {
    // 检查IP是否已存在
    if (cameras.data.some(cam => cam.cameraIP === camera_form.cameraIP)) {
      ElMessage.error("该摄像头IP已存在");
      return;
    }

    const newCamera = {
      rowID: `cam${String(cameras.data.length + 1).padStart(3, '0')}`,
      ...camera_form,
      companyName: companyName,
      status: "在线"
    };

    cameras.data.unshift(newCamera);
    camera_data.total = cameras.data.length;

    ElMessage({
      message: "设备添加成功",
      type: "success"
    });

    dialogVisibleDevice.value = false;
    resetCameraForm();
    get_cameras();
  } catch (error) {
    console.error("添加设备失败:", error);
    ElMessage.error("添加设备失败");
  }
};

// 重置摄像头表单
const resetCameraForm = () => {
  camera_form.cameraName = "";
  camera_form.cameraIP = "";
  camera_form.cameraPort = "";
  camera_form.loginUser = "";
  camera_form.loginPW = "";
  camera_form.longitude = "";
  camera_form.latitude = "";
  camera_form.pullUrl = "http://xxx.xxx.xxx.xxx:8080/live/设备ID.flv";
  camera_form.pushUrl = "rtmp://xxx.xxx.xxx.xxx:1935/live/设备ID";
  camera_form.hlsUrl = "http://xxx.xxx.xxx.xxx:8080/live/设备ID.m3u8";
  camera_form.areaName = "";
};

// 修改设备dialog
const dialogEditDevice = ref(false);

// 修改设备表单
const edit_camera_form = reactive({
  rowID: "",
  cameraName: "",
  cameraIP: "",
  cameraPort: "",
  loginUser: "",
  loginPW: "",
  longitude: "",
  latitude: "",
  pullUrl: "",
  pushUrl: "",
  hlsUrl: "",
  areaName: ""
});

// 编辑摄像头设备信息功能,回显数据
const handleEdit = (index, row) => {
  const camera = cameras.data.find(item => item.rowID === row.rowID);
  if (camera) {
    Object.assign(edit_camera_form, {
      rowID: camera.rowID,
      cameraName: camera.cameraName,
      cameraIP: camera.cameraIP,
      cameraPort: camera.cameraPort,
      loginUser: camera.loginUser,
      loginPW: camera.loginPW,
      longitude: camera.longitude,
      latitude: camera.latitude,
      pullUrl: camera.pullUrl,
      pushUrl: camera.pushUrl,
      hlsUrl: camera.hlsUrl,
      areaName: camera.areaName
    });

    dialogEditDevice.value = true;
  }
};

// 提交修改摄像头设备信息
const editSubmit = async () => {
  try {
    const index = cameras.data.findIndex(item => item.rowID === edit_camera_form.rowID);
    if (index !== -1) {
      // 检查IP是否已被其他设备使用
      const ipInUse = cameras.data.some(
          (cam, i) => i !== index && cam.cameraIP === edit_camera_form.cameraIP
      );

      if (ipInUse) {
        ElMessage.error("该摄像头IP已被其他设备使用");
        return;
      }

      Object.assign(cameras.data[index], {
        cameraName: edit_camera_form.cameraName,
        cameraIP: edit_camera_form.cameraIP,
        cameraPort: edit_camera_form.cameraPort,
        loginUser: edit_camera_form.loginUser,
        loginPW: edit_camera_form.loginPW,
        longitude: edit_camera_form.longitude,
        latitude: edit_camera_form.latitude,
        pullUrl: edit_camera_form.pullUrl,
        pushUrl: edit_camera_form.pushUrl,
        hlsUrl: edit_camera_form.hlsUrl,
        areaName: edit_camera_form.areaName
      });

      ElMessage({
        message: "设备修改成功",
        type: "success"
      });

      dialogEditDevice.value = false;
      get_cameras();
    }
  } catch (error) {
    console.error("修改设备失败:", error);
    ElMessage.error("修改设备失败");
  }
};

// 删除摄像头dialog
const deleteCameraVisible = ref(false);
const input_delete_data = ref("");

// 点击删除获取摄像头设备信息值
const remove_camera = reactive({
  id: null,
  cameraName: null
});

// 点击删除按钮
const handleDelete = (index, row) => {
  remove_camera.id = row.rowID;
  remove_camera.cameraName = row.cameraName;
  deleteCameraVisible.value = true;
  input_delete_data.value = "";
};

// 确认删除摄像头
const deleteCamera = async () => {
  try {
    if (input_delete_data.value === "确认删除") {
      const index = cameras.data.findIndex(item => item.rowID === remove_camera.id);
      if (index !== -1) {
        cameras.data.splice(index, 1);
        camera_data.total = cameras.data.length;

        ElMessage({
          message: "设备删除成功",
          type: "success"
        });

        deleteCameraVisible.value = false;
        input_delete_data.value = "";
        get_cameras();
      }
    } else {
      ElMessage.error("请输入'确认删除'以确认操作");
    }
  } catch (error) {
    console.error("删除设备失败:", error);
    ElMessage.error("删除设备失败");
  }
};

// 批量删除相关
const selectedCameras = ref([]);
const batchDeleteVisible = ref(false);
const batch_delete_data = ref("");

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedCameras.value = selection.map(item => item.rowID);
};

// 点击批量删除按钮
const handleBatchDelete = () => {
  if (selectedCameras.value.length === 0) {
    ElMessage.warning("请先选择要删除的设备");
    return;
  }
  batchDeleteVisible.value = true;
  batch_delete_data.value = "";
};

// 确认批量删除
const confirmBatchDelete = async () => {
  try {
    if (batch_delete_data.value === "确认删除") {
      // 从后往前删除避免索引问题
      for (let i = cameras.data.length - 1; i >= 0; i--) {
        if (selectedCameras.value.includes(cameras.data[i].rowID)) {
          cameras.data.splice(i, 1);
        }
      }

      camera_data.total = cameras.data.length;
      const deletedCount = selectedCameras.value.length;
      selectedCameras.value = [];

      ElMessage({
        message: `成功删除 ${deletedCount} 个设备`,
        type: "success"
      });

      batchDeleteVisible.value = false;
      batch_delete_data.value = "";
      get_cameras();
    } else {
      ElMessage.error("请输入'确认删除'以确认操作");
    }
  } catch (error) {
    console.error("批量删除失败:", error);
    ElMessage.error("批量删除失败");
  }
};

// 关闭dialog
const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？当前表单内容将不会保存', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    done();
  }).catch(() => {});
};

// 区域选项
const staticAreas = computed(() => {
  return areas.data;
});

// 搜索功能
const filteredCameras = () => {
  if (!searchKeyword.value) get_cameras();

  const keyword = searchKeyword.value.toLowerCase();
  camera_data.tableData = cameras.data.filter(camera =>
      camera.cameraName.toLowerCase().includes(keyword) ||
      camera.cameraIP.toLowerCase().includes(keyword) ||
      camera.areaName.toLowerCase().includes(keyword)
  );
}

const handleSearch = () => {
  camera_data.pageIndex = 1;
  filteredCameras();
};

const handleSearchClear = () => {
  camera_data.pageIndex = 1;
  get_cameras();
};

// 获取状态颜色
const getStatusColor = (status) => {
  switch(status) {
    case '在线': return '#75f365';
    case '离线': return '#ef3b3b';
    case '故障': return '#e7bf1f';
    default: return '#909399';
  }
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case '在线': return 'success';
    case '离线': return 'danger';
    case '故障': return 'warning';
    default: return 'info';
  }
};

onMounted(() => {
  getAreaTable();
  get_cameras();
});
</script>

<style scoped>
.container {
  padding: 20px;
  background: linear-gradient(135deg, #e0f7fa, #c8e6c9, #a5d6a7);
  min-height: 100vh;
  width: 100%;
}

.content-wrapper {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  width: 80%;
  margin: 0 auto;
}

.left-col, .right-col {
  padding: 15px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}


.section-header el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.area-management {
  background-color: #f9fafc;
  border-radius: 8px;
  padding: 15px;
  height: 100%;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.device-management {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  height: 100%;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.add-btn {
  width: 100%;
  margin-bottom: 15px;
  display: flex;

}

.tree-container {
  height: calc(100% - 50px);
  overflow-y: auto;
}

.custom-tree {
  background-color: transparent;
}

.custom-tree :deep(.el-tree-node__content) {
  height: 36px;
}

.custom-tree :deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409EFF;
  font-weight: 500;
}

.device-controls {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
  align-items: center;
}

.device-controls .el-button {
  flex-shrink: 0;
}

.search-box {
  flex-grow: 1;
  margin-left: 10px;
}

.device-table {
  margin-top: 15px;
}



.custom-table {
  width: 100%;
  border-radius: 6px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header) th {
  background-color: #f5f7fa;
  font-weight: 600;
  font-size: 18px;
}

.custom-table :deep(.el-table__row) {
  transition: background-color 0.3s;
  font-size: 16px;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-confirm, .batch-delete-confirm {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 15px;
}

.confirm-text {
  margin: 15px 0 10px;
  font-size: 16px;
}

.confirm-hint {
  color: #909399;
  font-size: 14px;
  margin-bottom: 15px;
}

.custom-input {
  width: 100%;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 1200px) {
  .el-col {
    width: 100%;
  }

  .left-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .device-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    margin-left: 0;
    margin-top: 10px;
  }

  .content-wrapper {
    padding: 10px;
  }
}
</style>